import React, { Suspense, useState, useEffect } from "react";
import {
  createBrowserRouter,
  RouterProvider,
  Navigate,
} from "react-router-dom";
import "antd-mobile/es/global"; // 确保全局样式已导入

// 动态导入所有路由组件
const componentMap = import.meta.glob("/src/views/**/*.tsx");
// 假设你的主布局组件路径是 /src/views/Mains.tsx
const Mains = (await import("/src/views/Mains/Mains.tsx")).default;
export default function AppRouter() {
  const [routes, setRoutes] = useState([]);

  useEffect(() => {
    // 1. 首先加载主布局组件（Mains）
    const loadMainLayout = async () => {
      try {
        // 动态生成路由配置
        const generatedRoutes = Object.keys(componentMap)
          .filter((path) => path !== "/src/views/Mains/Mains.tsx") // 排除主布局组件
          .map((path) => {
            const routePath = path
              .replace("/src/views", "")
              .replace(".tsx", "")
              .replace("/index", "");

            return {
              path: routePath,
              element: (
                <Suspense fallback={<div>Loading...</div>}>
                  {React.createElement(React.lazy(() => componentMap[path]()))}
                </Suspense>
              ),
            };
          });

        setRoutes(generatedRoutes);
      } catch (error) {
        console.error("路由加载失败:", error);
      }
    };
    loadMainLayout();
  }, []);

  // 如果 routes 为空，返回加载状态
  if (routes.length === 0) return <div>Loading...</div>;
  const MainsChild = routes
    .map((item) => {
      // 确保item存在且包含path属性
      if (!item || !item.path) return null;

      // 分割路径并过滤空字符串
      const pathSegments = item.path
        .split("/")
        .filter((segment) => segment !== "");
      if (pathSegments.length === 1) {
        // 修正：改为1，因为分割后["", "about"]会变成["about"]
        return item;
      }
      return null;
    })
    .filter((item) => item !== null); // 过滤掉undefined/null的项
  const routess = routes
    .map((item) => {
      // 确保item存在且包含path属性
      if (!item || !item.path) return null;

      // 分割路径并过滤空字符串
      const pathSegments = item.path
        .split("/")
        .filter((segment) => segment !== "");
      if (pathSegments.length > 1) {
        // 修正：改为1，因为分割后["", "about"]会变成["about"]
        return item;
      }
      return null;
    })
    .filter((item) => item !== null); // 过滤掉undefined/null的项
  console.log(routess);

  // 创建路由器（此时 routes 已经填充）
  const router = createBrowserRouter([
    {
      path: "/",
      element: <Mains />,
      children: [
        // {
        //   path: "/",
        //   element: <Navigate to="/home" replace />, // 重定向到 /home
        // },
        ...MainsChild,
      ],
    },
    // {
    //   path: "/",
    //   element: <Navigate to="/home" replace />, // 重定向到 /home
    // },
    ...routess,
    {
      path: "*",
      element: <div>404 Not Found</div>,
    },
  ]);
  // console.log("router", router);

  return (
    <Suspense fallback={<div>Loading...</div>}>
      <RouterProvider router={router} />
    </Suspense>
  );
}
